// http
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <cstring>

#define PORT 8087

void handle_client(int client_socket,const char* response) {
    char buffer[1024] = {0};
    read(client_socket, buffer, 1024);
    std::cout << "Request:\n" << buffer << std::endl;

    // const char* response = 
    //     "HTTP/1.1 200 OK\r\n"
    //     "Content-Type: text/html\r\n\r\n"
    //     "<html><body><h1>Hello, World!</h1></body></html>";
    
    write(client_socket, response, strlen(response));
    close(client_socket);
}

void run(const char* response){
    int server_fd, client_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);

    // 1. 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("Socket failed");
        exit(EXIT_FAILURE);
    }

    // 2. 绑定地址和端口
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
        perror("Bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 3. 监听连接
    if (listen(server_fd, 3) < 0) {
        perror("Listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    std::cout << "Server is listening on port " << PORT << std::endl;

    // 4. 接受客户端连接并处理请求
    while (true) {
        if ((client_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) {
            perror("Accept failed");
            close(server_fd);
            exit(EXIT_FAILURE);
        }

        // 处理客户端请求
        handle_client(client_socket, response);
    }

    close(server_fd);
}

// int main() {
//     //copy code
//     run("HTTP/1.1 200 OK\r\n"
//         "Content-Type: text/html\r\n\r\n"
//         "<html><body><h1>Hello, World!!!!</h1></body></html>");
//     return 0;
// }